package com.example.song.mywebviewclient;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.text.TextUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author txs
 * @date 2018/11/05
 * @package com.example.song.mywebviewclient
 */
public class CopyAssetsToSd {

    private static final String SEPARATOR = File.separator;//路径分隔符
    final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 5, 1, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(100));
    private Context mContext;
    /**
     * assets的文件夹 js
     */
    private String assetDir;
    /**
     * 目标文件夹
     */
    private String dir;

    public CopyAssetsToSd(Context context, String assetDir, String dir) {
        mContext = context;
        this.assetDir = assetDir;
        this.dir = dir;
        new MyAsyncTask().execute();
    }

    /**
     * 监听复制完成
     */
    public interface onCopyListener {
        void success();
    }

    private onCopyListener mOnCopyListener;

    public void setOnCopyListener(onCopyListener onCopyListener) {
        this.mOnCopyListener = onCopyListener;
    }

    public void copyAssets(final String assetDir, final String dir) {
        this.assetDir = assetDir;
        this.dir = dir;
        if (TextUtils.isEmpty(dir)) {
            return;
        } else if (dir.endsWith(SEPARATOR)) {
            this.dir = dir.substring(0, dir.length() - 1);
        }

        if (TextUtils.isEmpty(assetDir) || assetDir.equals(SEPARATOR)) {
            this.assetDir = "";
        } else if (assetDir.endsWith(SEPARATOR)) {
            this.assetDir = assetDir.substring(0, assetDir.length() - 1);
        }
        threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                String temp = "";
                AssetManager assetManager = mContext.getAssets();
                try {
                    File file = new File(dir);
                    if (!file.exists()) {//如果文件夹不存在，则创建新的文件夹
                        file.mkdirs();
                    }

                    // 获取assets目录下的所有文件及目录名
                    String[] fileNames = assetManager.list(assetDir);
                    if (fileNames.length > 0) {//如果是目录 apk
                        for (String fileName : fileNames) {
                            if (!TextUtils.isEmpty(assetDir)) {
                                temp = assetDir + SEPARATOR + fileName;//补全assets资源路径
                            }

                            String[] childFileNames = assetManager.list(temp);
                            if (!TextUtils.isEmpty(temp) && childFileNames.length > 0) {//判断是文件还是文件夹：如果是文件夹
                                copyAssets(temp, dir + SEPARATOR + fileName);
                            } else {//如果是文件
                                InputStream inputStream = assetManager.open(temp);
                                readInputStream(dir + SEPARATOR + fileName, inputStream);
                            }
                        }
                    } else {//如果是文件 doc_test.txt或者apk/app_test.apk
                        InputStream inputStream = assetManager.open(assetDir);
                        String myAssetDir = "";
                        if (assetDir.contains(SEPARATOR)) {//apk/app_test.apk
                            myAssetDir = assetDir.substring(assetDir.lastIndexOf(SEPARATOR), assetDir.length());
                        }
                        readInputStream(dir + SEPARATOR + myAssetDir, inputStream);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });


    }

    /**
     * 读取输入流中的数据写入输出流
     *
     * @param dir         目标文件路径
     * @param inputStream 输入流
     */
    private void readInputStream(String dir, InputStream inputStream) {
        File file = new File(dir);
        try {
            if (!file.exists()) {
                // 1.建立通道对象
                FileOutputStream fos = new FileOutputStream(file);
                // 2.定义存储空间
                byte[] buffer = new byte[inputStream.available()];
                // 3.开始读文件
                int lenght = 0;
                while ((lenght = inputStream.read(buffer)) != -1) {// 循环从输入流读取buffer字节
                    // 将Buffer中的数据写到outputStream对象中
                    fos.write(buffer, 0, lenght);
                }
                fos.flush();// 刷新缓冲区
                // 4.关闭流
                fos.close();
                inputStream.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    class MyAsyncTask extends AsyncTask<String, Void, Bitmap> {

        //onPreExecute用于异步处理前的操作
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        //在doInBackground方法中进行异步任务的处理.
        @Override
        protected Bitmap doInBackground(String... params) {
            copyAssets(assetDir, dir);
            return null;
        }

        //onPostExecute用于UI的更新.此方法的参数为doInBackground方法返回的值.
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if (mOnCopyListener != null) {
                mOnCopyListener.success();
            }

        }
    }
}





